package com.lframework.xingyun.basedata.impl.coupon;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageInfo;
import com.lframework.starter.web.core.impl.BaseMpServiceImpl;
import com.lframework.starter.web.core.utils.PageResultUtil;
import com.lframework.starter.web.core.components.resp.PageResult;
import com.lframework.starter.web.core.utils.OpLogUtil;
import java.io.Serializable;
import com.lframework.starter.common.exceptions.impl.DefaultClientException;
import com.lframework.starter.web.core.utils.IdUtil;
import com.lframework.starter.common.utils.ObjectUtil;
import com.lframework.starter.web.core.annotations.oplog.OpLog;
import com.lframework.starter.common.utils.Assert;
import com.lframework.starter.web.inner.components.oplog.OtherOpLogType;
import com.lframework.xingyun.basedata.bo.coupon.GetCouponBo;
import com.lframework.xingyun.basedata.entity.Coupon;
import com.lframework.xingyun.basedata.entity.CouponProduct;
import com.lframework.xingyun.basedata.entity.CouponStop;
import com.lframework.xingyun.basedata.mappers.CouponMapper;
import com.lframework.xingyun.basedata.service.coupon.CouponProductService;
import com.lframework.xingyun.basedata.service.coupon.CouponService;
import com.lframework.xingyun.basedata.service.coupon.CouponStopService;
import com.lframework.xingyun.basedata.vo.coupon.CreateCouponVo;
import com.lframework.xingyun.basedata.vo.coupon.QueryCouponVo;
import com.lframework.xingyun.basedata.vo.coupon.UpdateCouponVo;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class CouponServiceImpl extends BaseMpServiceImpl<CouponMapper, Coupon> implements CouponService {

    @Override
    public PageResult<Coupon> selector(Integer pageIndex, Integer pageSize, QueryCouponVo vo) {
        Assert.greaterThanZero(pageIndex);
        Assert.greaterThanZero(pageSize);

        IPage<Coupon> page = getBaseMapper().queryPage(vo);

        return PageResultUtil.convert(page);
    }

    @Override
    public PageResult<Coupon> queryPage(Integer pageIndex, Integer pageSize, QueryCouponVo vo) {

        Assert.greaterThanZero(pageIndex);
        Assert.greaterThanZero(pageSize);

        IPage<Coupon> page = getBaseMapper().queryPage(vo);

        return PageResultUtil.convert(page);
    }

    @Override
    public List<Coupon> queryList(QueryCouponVo vo) {
        return getBaseMapper().queryList(vo);
    }

    @Cacheable(value = Coupon.CACHE_NAME, key = "@cacheVariables.tenantId() + #id", unless = "#result == null")
    @Override
    public Coupon findById(String id) {
        return getBaseMapper().selectById(id);
    }

    @OpLog(type = OtherOpLogType.class, name = "新增卡券信息，ID：{}", params = {"#id"})
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String create(CreateCouponVo vo) {

        Coupon data = new Coupon();
        data.setId(IdUtil.getId());
        data.setCouponType(vo.getCouponType());
        data.setCouponName(vo.getCouponName());
        data.setSendWay(vo.getSendWay());
        data.setEffectiveDay(vo.getEffectiveDay());
        data.setAvailable(vo.getAvailable());
        data.setDescription(vo.getDescription());
        data.setParValue(vo.getParValue());
        data.setAdded(vo.getAdded());
        data.setUseCondition(vo.getUseCondition());
        data.setPrice(vo.getPrice());
        data.setProductAll(vo.getProductAll());
        data.setStopAll(vo.getStopAll());

        getBaseMapper().insert(data);

        getThis(CouponService.class).batchAddCouponStops(vo.getStopAll(), data.getId(), StrUtil.split(vo.getShopIds(), StrUtil.COMMA));

        getThis(CouponService.class).batchAddCouponProducts(vo.getProductAll(), data.getId(), StrUtil.split(vo.getProductIds(), StrUtil.COMMA));

        OpLogUtil.setVariable("id", data.getId());
        OpLogUtil.setExtra(vo);

        return data.getId();
    }

    @OpLog(type = OtherOpLogType.class, name = "修改卡券信息，ID：{}", params = {"#id"})
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void update(UpdateCouponVo vo) {

        Coupon data = getBaseMapper().selectById(vo.getId());
        if (ObjectUtil.isNull(data)) {
            throw new DefaultClientException("卡券信息不存在！");
        }

        LambdaUpdateWrapper<Coupon> updateWrapper = Wrappers.lambdaUpdate(Coupon.class)
                .set(Coupon::getCouponType, vo.getCouponType())
                .set(Coupon::getCouponName, vo.getCouponName())
                .set(Coupon::getSendWay, vo.getSendWay())
                .set(Coupon::getEffectiveDay, vo.getEffectiveDay())
                .set(Coupon::getAvailable, vo.getAvailable())
                .set(Coupon::getDescription, vo.getDescription())
                .set(Coupon::getParValue, vo.getParValue())
                .set(Coupon::getAdded, vo.getAdded())
                .set(Coupon::getUseCondition, vo.getUseCondition())
                .set(Coupon::getPrice, vo.getPrice())
                .set(Coupon::getProductAll, vo.getProductAll())
                .set(Coupon::getStopAll, vo.getStopAll())
                .eq(Coupon::getId, vo.getId());

        getBaseMapper().update(updateWrapper);

        getThis(CouponService.class).batchAddCouponStops(vo.getStopAll(), data.getId(), StrUtil.split(vo.getShopIds(), StrUtil.COMMA));

        getThis(CouponService.class).batchAddCouponProducts(vo.getProductAll(), data.getId(), StrUtil.split(vo.getProductIds(), StrUtil.COMMA));

        OpLogUtil.setVariable("id", data.getId());
        OpLogUtil.setExtra(vo);
    }

    @CacheEvict(value = Coupon.CACHE_NAME, key = "@cacheVariables.tenantId() + #key")
    @Override
    public void cleanCacheByKey(Serializable key) {

    }

    @Transactional(rollbackFor = Exception.class)
    public void batchAddCouponStops(Boolean isAll, String couponId, List<String> stopIds) {
        getThis(CouponStopService.class).remove(Wrappers.lambdaQuery(CouponStop.class).eq(CouponStop::getCouponId, couponId));
        if (!isAll) {
            List<CouponStop> stops = Optional.ofNullable(stopIds).orElseGet(ArrayList::new).stream().map(stopId -> {
                CouponStop couponStop = new CouponStop();
                couponStop.setCouponId(couponId);
                couponStop.setStopId(stopId);

                return couponStop;
            }).collect(Collectors.toList());

            if (CollUtil.isNotEmpty(stops)) {
                getThis(CouponStopService.class).saveBatch(stops);
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void batchAddCouponProducts(Boolean isAll, String couponId, List<String> productIds) {
        getThis(CouponProductService.class).remove(Wrappers.lambdaQuery(CouponProduct.class).eq(CouponProduct::getCouponId, couponId));
        if (!isAll) {
            List<CouponProduct> couponProducts = Optional.ofNullable(productIds).orElseGet(ArrayList::new).stream().map(productId -> {
                CouponProduct couponProduct = new CouponProduct();
                couponProduct.setCouponId(couponId);
                couponProduct.setProductId(productId);
                couponProduct.setProductNum(0);

                return couponProduct;
            }).collect(Collectors.toList());

            if (CollUtil.isNotEmpty(couponProducts)) {
                getThis(CouponProductService.class).saveBatch(couponProducts);
            }
        }
    }
}

